package com.fengwan.wastesort.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.fengwan.wastesort.R
import com.fengwan.wastesort.adapter.WasteSortAdapter
import com.fengwan.wastesort.adapter.WasteSortAdapter2
import com.fengwan.wastesort.model.Waste
import com.fengwan.wastesort.ui.viewModel.WasteHarmfulViewModel
import kotlinx.android.synthetic.main.fragment_waste_sort.*

class WasteHarmfulFragment : BaseWasteFragment(), BaseQuickAdapter.RequestLoadMoreListener, Observer<List<Waste>> {

    companion object {
        fun newInstance() = WasteHarmfulFragment()
    }

    private val adapter by lazy { WasteSortAdapter2(activity!!) }
    private val viewModel by lazy { ViewModelProviders.of(this).get(WasteHarmfulViewModel::class.java) }
    private var isFirst = true

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_waste_sort, container, false)
    }

    override fun initListener() {
        viewModel.harmfulWastes.observe(this, this)
    }


    override fun initView(view: View) {
        recycler.layoutManager = GridLayoutManager(context, 2, RecyclerView.VERTICAL, false)
        val itemHeader = getItemHeader(R.layout.item_waste_header, recycler)
//        adapter.setHeaderView(itemHeader)
        setItemHeaderContent(
            itemHeader,
            R.color.colorWasteHarmful,
            "有害垃圾",
            R.mipmap.icon_hazardous,
            "指对人体健康或者自然环境造成直接或潜在危害的废弃物\n如废镍镉电池和废氢化汞电池、废银光灯管、废药品及其包装物、废油漆和溶剂及其包装物、废含汞温度计和血压计、废杀虫剂消毒剂及其包装物、废胶片及其相纸。\n◆分类投放有害垃圾时，应注意轻放\n◆易碎尖锐的，应连带包装或包裹后投放\n◆压力罐装容器，应排空内容物后投放"
        )


//        adapter.setOnLoadMoreListener(this, recycler)
        recycler.adapter = adapter
    }

    override fun loadData(_id: Int, type: Int) {
        viewModel.loadHarmfulWastes(_id)
    }

    override fun onLoadMoreRequested() {
//        loadData(adapter.data[adapter.data.size - 1]._id)
    }

    override fun onChanged(it: List<Waste>) {
        if (it.any()) {
            if (isFirst) {
                adapter.setNewData(it)
                isFirst = false
            } else {
                adapter.addData(it)
            }
//            adapter.loadMoreComplete()
        } else {
//            adapter.loadMoreEnd(true)
        }
    }

    override fun onDestroyView() {
        viewModel.harmfulWastes.removeObserver(this)
        super.onDestroyView()
    }


}
